<template>
  <div class="rolesIndex">
         <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- card卡片 -->
<el-card class="box-card">
  <div>
    <el-row>
  <el-button type="primary" @click="addingRoles">添加角色</el-button>
</el-row>
  <el-table
    :data="rolesData"
    border
    style="width: 100%">
      <el-table-column
      type="expand"
      width="50">
      <template slot-scope="scope">
        <!-- <pre>
          {{scope.row}}
        </pre> -->
        <!-- 一级 -->
      <el-row :class="['borderBottom',i1===0?'borderTop':'']" v-for="(item,i1) in scope.row.children" :key="item.id">
      <el-col :span="5">
         <el-tag closable @close="deleteRight(scope.row,item.id)">{{item.authName}}</el-tag>
         <i class="el-icon-caret-right"></i>
      </el-col>
      <el-col :span="19">
        <!-- 二级、三级 -->
    <el-row :class="[i2===0?'':'borderTop']" v-for="(item2,i2) in item.children" :key="item2.id">
      <el-col :span="6">
       <el-tag closable @close="deleteRight(scope.row,item2.id)" type="success">{{item2.authName}}</el-tag>
       <i class="el-icon-caret-right"></i>
      </el-col>
        <el-col :span="18">
            <el-tag closable @close="deleteRight(scope.row,item3.id)" v-for="(item3,) in item2.children" :key="item3.id" type="warning">{{item3.authName}}</el-tag>
      </el-col>
    </el-row>
      </el-col>
      </el-row>
      </template>
    </el-table-column>
    <el-table-column
      type="index"
      width="50">
    </el-table-column>
    <el-table-column
      prop="roleName"
      label="角色名称"
      >
    </el-table-column>
    <el-table-column
      prop="roleDesc"
      label="角色描述"
      >
    </el-table-column>
    <el-table-column
      label="操作"
        >
        <template slot-scope="scope">
          <div class="tableBtn">
            <!-- 修改用户按钮 -->
            <el-button @click="amendUsers(scope.row.id)" type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
            <!-- 删除用户按钮 -->
            <el-button @click="deleteUser(scope.row.id)" type="danger" size="mini" icon="el-icon-delete">删除</el-button>
           <el-button @click="clickAllot(scope.row)" type="warning" size="mini" icon="el-icon-share">分配权限</el-button>
          </div>
        </template>
    </el-table-column>
  </el-table>
  </div>
  <!-- 添加对话框 -->
  <el-dialog
  title="添加角色"
  :visible.sync="rolesVisible"
  width="50%"
  >
  <div>
    <el-form :model="addruleForm"
    ref="addruleForm"
    :rules="rules"
    label-width="100px">
   <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="addruleForm.roleName"></el-input>
  </el-form-item>
     <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="addruleForm.roleDesc"></el-input>
  </el-form-item>
</el-form>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="clickRoles">确 定</el-button>
    <el-button @click="rolesVisible = false">取 消</el-button>
    <el-button @click="resetForm('addruleForm')">重置</el-button>
  </span>
</el-dialog>
<!-- 修改角色对话框 -->
 <el-dialog
  title="编辑角色"
  :visible.sync="alterRolesVisible"
  width="50%"
  >
  <div>
    <el-form :model="alterruleForm"
    ref="alterruleForm"
    :rules="rules"
    label-width="100px">
   <el-form-item label="角色名称" prop="roleName">
    <el-input v-model="alterruleForm.roleName"></el-input>
  </el-form-item>
     <el-form-item label="角色描述" prop="roleDesc">
    <el-input v-model="alterruleForm.roleDesc"></el-input>
  </el-form-item>
</el-form>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="clickAlterRoles">确 定</el-button>
    <el-button @click="alterRolesVisible = false">取 消</el-button>
    <el-button @click="alterForm('alterruleForm')">重置</el-button>
  </span>
</el-dialog>
<!-- 分配权限 -->
<el-dialog
  title="分配权限"
  :visible.sync="authorityDistribution"
  width="50%"
  @close="closedefaultKeysList"
  >
  <!--
    default-checked-keys	默认勾选的节点的 key 的数组	array
   -->
   <el-tree
  :data="authorityData"
  show-checkbox
  default-expand-all
  :default-checked-keys="defaultKeysList"
  node-key="id"
  ref="treelist"
  :props="treeProps">
</el-tree>

  <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="AllAlterRoles">确 定</el-button>
    <el-button @click="authorityDistribution = false">取 消</el-button>
  </span>
</el-dialog>
</el-card>
  </div>
</template>

<script>
import {getRoles,postRoles,getRolesId,putRolesId,deleteRolesId,deleteRolesRoleId,gitRightsTree,postRolesRoleIdRights} from '@/api/right'
export default {
  name:'rolesIndex',
  data() {
    return {
        rolesData:[],
        rolesVisible:false,//添加角色
         addruleForm:{
        roleName:'',
        roleDesc:''
     },
        rules:{
            roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
        },
        alterRolesVisible:false,//编辑角色
        alterruleForm:[],
        authorityForm:[],//分配权限
        authorityDistribution:false,//分配权限
        authorityData:[],//分配权限，数据存储
        treeProps: {
          label: 'authName',
          children: 'children'
        },
        defaultKeysList:[],//存放默认展开节点
        roleId:''
    }
  },
  created(){
    this.rolesDataList()
  },
  methods:{
    // 获取数据
    async rolesDataList(){
       const {data} = await getRoles();
      //  console.log(data, '')
       this.rolesData = data.data;
    },
    // 添加角色按钮
    addingRoles(){
       this.rolesVisible=true;
    },
    // 重置
     resetForm() {
        this.$refs.addruleForm.resetFields();
      },
    // 创建用户
    async clickRoles(){
      const {data} = await postRoles(this.addruleForm)
      console.log(data, '')
      if(data.meta.status!==201){
       return this.$message.error(data.meta.msg)
      }
        this.rolesDataList();
        this.$message.success(data.meta.msg);
        this.rolesVisible=false;
    },
  //  修改，根据 ID 查询角色
   async amendUsers(id){
     const {data} = await getRolesId(id);
     this.alterruleForm = data.data;
     console.log(data, '')
     this.alterRolesVisible = true
   },
   //编辑列表，重置
   alterForm(){
   this.$refs.alterruleForm.resetFields();
   },
  //  编辑提交角色

 async clickAlterRoles(){
   const {data} = await putRolesId(this.alterruleForm);
   console.log(data, '')
     if(data.meta.status!==200){
       return this.$message.error(data.meta.msg)
      }
        this.rolesDataList();
        this.$message.success(data.meta.msg);
        this.alterRolesVisible=false;
 },
//  删除角色
  async deleteUser(id){
    const res = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err);
        if(res !== 'confirm')return this.$message.info('取消了删除')
       const {data} = await deleteRolesId(id);
       this.$message.success(data.meta.msg);
       this.alterRolesVisible = false
       this.rolesDataList()
},
// 删除指定角色权限
    async deleteRight(role,right){
      let res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(res !== "confirm")return this.$message.info('取消了删除!!!')
      const {data} = await deleteRolesRoleId(role.id,right)
      if(data.meta.status !==200)return this.$message.error(data.meta.msg)
      role.children=data.data;
      this.$message.success(data.meta.msg);
      console.log(data, '')
    },
//分配权限
async clickAllot(role){
  this.roleId = role.id
   let {data} = await gitRightsTree();
   console.log(data, '分配权限')
   this.authorityData = data.data;
   console.log(this.authorityData, '分配权限1')
  //  递归获取三级节点的ID
   this.recursiveData(role,this.defaultKeysList)
   console.log(role, '递归获取三级节点')
   this.authorityDistribution=true;
},
//定义一个方法，使用递归存放已有节点数据
  // 其中方法里面包含两个属性，node用于查找三级节点，arr用于数组
recursiveData(node,arr){
// 判断是否是三级节点
if(!node.children){
  return arr.push(node.id)
}
node.children.forEach(item =>{
  this.recursiveData(item,arr)
})
},
// 清空上次分配权限存储
closedefaultKeysList(){
  this.defaultKeysList=[]
},
// 分配权限把选中数据存到后台服务器
async AllAlterRoles(){
 // getCheckedKeys	若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组	(leafOnly) 接收一个 boolean 类型的参数，若为 true 则仅返回被选中的叶子节点的 keys，默认值为 false
//getHalfCheckedKeys	若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点的 key 所组成的数组

  const AllArrayList=[
    ...this.$refs.treelist.getCheckedKeys(),
    ...this.$refs.treelist.getHalfCheckedKeys()
  ]
  const IdStr = AllArrayList.join(',')
  console.log(IdStr, 'getCheckedKeysaAAAAAAAAAAAAAAAAAAAA')
  const {data} = await postRolesRoleIdRights(this.roleId,IdStr);
  console.log(data, '298')
  this.rolesDataList();
  this.authorityDistribution=false;
}
  }
}
</script>

<style lang="less" scoped>
.rolesIndex{
  .el-tag{
    margin:7px
  }
    .el-row{
    display: flex;
    flex-direction: row;
    align-items: center;

    }
  .borderBottom{
    border-bottom: 1px solid #ccc;
  }
   .borderTop{
    border-top: 1px solid #ccc;
  }
}
</style>
